package com.ln.prac.lianglianglee;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 一个2T的文件，每一行为一个数字，给定限制512M的内存，如何找出其中出现次数最多的数字
 * 1、兼顾性能越优越好
 * 2、可以用任何熟悉的语言
 *
 * @Author zhangj
 * @Date 2023/6/29 22:47
 */
public class StaticNum {

    @Test
    public void test() throws IOException {
        System.out.println(staticNum("/Users/junjun/Downloads/test.txt"));
    }

    public long staticNum(String filePath) throws IOException {
        int size = 512 * 1024 * 1024;
        int index = 0;
        long result = Integer.MIN_VALUE;
        long maxCnt = Integer.MIN_VALUE;

        long[] numCnt = new long[Integer.MAX_VALUE / 2];

        RandomAccessFile raf = null;

        while (true) {
            try {
                raf = new RandomAccessFile(filePath, "r");
                int seek = index * size;
                if(seek > raf.length()) {
                    break;
                }
                raf.seek(seek);
                index += 1;
                int remain = size;
                String line;
                while (remain > 0) {
                    line = raf.readLine();
                    int position = 0;

                    for (char c : line.toCharArray()) {
                        int cn = c - '0';
                        position |= cn;
                        position <<= 4;
                    }
                    position >>= 4;
                    if (++numCnt[position] > maxCnt) {
                        result = Integer.parseInt(line);
                    }
                    remain -= line.length() + 1;
                }

            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } finally {
                if (raf != null) {
                    raf.close();
                }
                return result;
            }
        }


    }

}
